/**
 * @Author: yzy
 * @Description:
 * @Version: 1.0.0
 * @Date: 2021/12/24 19:41
 * @Copyright: MIN-Group；国家重大科技基础设施——未来网络北大实验室；深圳市信息论与未来网络重点实验室
 */
package vms

import (
	"fmt"
	"log"
	"os"
	"time"
	"vpn-management-server/config"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/keymanager"
	"vpn-management-server/src/controller/usercontroller"
	"vpn-management-server/src/dao"
	"vpn-management-server/src/router"
	"vpn-management-server/src/service/authservice"
	"vpn-management-server/src/service/userlogservice"
	"vpn-management-server/src/service/userservice"
)

func vmsShow() {
	var vms = "\033[1;35;48m _     _       ___  ___   _____  \n| |   / /     /   |/   | /  ___/ \n| |  / /     / /|   /| | | |___  \n| | / /     / / |__/ | | \\___  \\ \n| |/ /     / /       | |  ___| | \n|___/     /_/        |_| /_____/  \033[0m "
	fmt.Fprintln(os.Stdout, vms)
}

func Start(vpnConfig *config.VPNConfig) {
	vmsShow()
	logger.Logger.Init(vpnConfig)
	dao.GMysqlDB.Init(vpnConfig)
	dao.RdsClient.Init(vpnConfig.RedisConfig)
	network.Init(vpnConfig)
	authservice.Init(vpnConfig.SessionConfig)
	userservice.Init(vpnConfig.MinSDKConfig)
	userlogservice.Init(vpnConfig)
	key := keymanager.New(vpnConfig.FESSLConfig.Pubkey, vpnConfig.FESSLConfig.Prikey)
	RecoverCoroutines("StartMINRouter", router.StartMINRouter, 5*time.Second)
	RecoverCoroutines("StartCPacketRouter", router.StartCPacketRouter, 5*time.Second)
	RecoverCoroutines("StartMINSecRouter", router.StartMINSecRouter, 5*time.Second)
	go router.StartSecRouter(vpnConfig.GetFEAddress(), vpnConfig.GetFESSLAddress(), key)

	go usercontroller.StartHandleSimAuthCallback()

	select {}
}

func RecoverCoroutines(name string, f func() error, duration time.Duration) {
	go func() {

		for {
			if err := f(); err != nil {
				log.Printf("----------[%s] restart ----------\n", name)
				time.Sleep(duration)
			}
		}

	}()
}
